import { app, protocol, BrowserWindow,ipcMain } from 'electron'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'
import ListenersEvent from "../main/ListenersEvent"
import autoUpdater from '../main/update'
import os from "os"

const isDevelopment = process.env.NODE_ENV !== 'production'
let win
protocol.registerSchemesAsPrivileged([{scheme: 'app', privileges: { secure: true, standard: true } }])
function createWindow () {
    win = new BrowserWindow({
        width: 1280, 
        height: 800, 
        resizable:false,
        // width:1920,
        // height:1080,
        frame:false,
        // useContentSize:true,
        webPreferences: {
            nodeIntegration: true
        },
    })
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
            
    } else {
        createProtocol('app')
        win.loadURL('app://./index.html')
    }
    const eventList=new ListenersEvent()
    const eventListFuns=Object.getOwnPropertyNames(Object.getPrototypeOf(eventList))
    if(eventListFuns[0]===constructor) eventListFuns.splice(0,1)
    eventListFuns.forEach(el=>{
        ipcMain.on(el,eventList[el]);
    })
    ipcMain.on('focus_main',function(){
        win.focus()
        win.show()
    })
    ipcMain.on('close',()=>app.exit())
    win.on('closed', () => {
        win = null
    })
    ipcMain.on('devTools',function(){
        win.webContents.openDevTools()
    })
}
if(os.release().startsWith('6.1'))
    app.disableHardwareAcceleration()
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

app.on('ready', async () => {
    if (isDevelopment && !process.env.IS_TEST) {
        // 
    }
    if(process.env.NODE_ENV == 'production')
        autoUpdater.checkForUpdates()
    createWindow()
  
})



/*
const gotTheLock = app.requestSingleInstanceLock()
// fs.appendFile('d:/a.txt','1',new Function)

if (!gotTheLock) {
    // fs.appendFile('d:/a.txt','2',new Function)
  app.quit()
} else {
    // fs.appendFile('d:/a.txt','3',new Function)
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // fs.appendFile('d:/a.txt','4',new Function)
    // 当运行第二个实例时,将会聚焦到win这个窗口
    if (win) {
        // fs.appendFile('d:/a.txt','5',new Function)
      if (win.isMinimized()) win.restore()
      win.focus()
      win.show()
    }
  })
}
*/

if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', data => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}


